<?php

class Mailer extends Controller {

	function Mailer() {
		parent::Controller();
		$this->load->model('model_mailer');
		$this->fromSession = $this->usersession->currentUser();
		copyPost($this->aPost);
		if ($this->fromSession["user_id"] == "") {
			$aResponse = array(
				"error" => TRUE,
				"description" => "Sesiunea a expirat",
				"type" => "nosession"
			);
			die(json_encode($aResponse));
		}
	}

	function bringMailer() {

		$table = 'mailer';
		$s_limit = $this->input->post("start");
		$e_limit = $this->input->post("limit");
		$dir = $this->input->post("dir");
		$sort = $this->input->post("sort");
		$query = $this->input->post("query");
		if ($sort == "name")
			$sort = "mailer.name";
		if ($sort == "client_name")
			$sort = "client.name";

		echo json_encode($this->model_mailer->bringMailer($table, $s_limit, $e_limit, $sort, $dir, $query));
	}

	/**
	 * Functie de add simplu ( nume +client_id)
	 */
	function addMailer() {

		$data["name"] = $this->input->post("name");
		$data["client_id"] = $this->input->post("client_id");

		$bResult = $this->model_mailer->addMailer($data);
		if (!$bResult) {
			$aResponse = array(
				"error" => TRUE,
				"description" => "Exista duplicat pe campania selectata",
				"type" => "data"
			);
			echo json_encode($aResponse);
			return;
		}

		$aResponse = array(
			"error" => FALSE,
			"description" => "Mailerul a fost adaugat",
			"success" => TRUE
		);
		echo json_encode($aResponse);
	}

	function deleteMailer() {
		$this->model_mailer->deleteMailer($_POST);
		$aResponse = array(
			"error" => FALSE,
			"description" => "Datele au fost sterse",
			"success" => TRUE
		);
		echo json_encode($aResponse);
	}

	function getMailerData() {
		$idMailer = $this->input->post("idMailer");


		$array = $this->model_mailer->getMailerSettings($idMailer);
		$aResponse = array(
			"success" => TRUE,
			"data_settings" => $array
		);

		$sort = "name";
		$dir = "asc";
		$aResponse_image = $this->model_mailer->bringAttach("mailer_attach", $idMailer, "image", $s_limit, $e_limit, $sort, $dir);
		$aResponse = array_merge($aResponse, $aResponse_image);

		$sort = "name";
		$dir = "asc";
		$aResponse_attach = $this->model_mailer->bringAttach("mailer_attach", $idMailer, "attach", $s_limit, $e_limit, $sort, $dir);
		$aResponse = array_merge($aResponse, $aResponse_attach);

		//linkuri
		$sort = "link_nume";
		$dir = "asc";
		$aResponse_link = $this->model_mailer->bringLink("mailer_link", $idMailer, $s_limit, $e_limit, $sort, $dir);
		$aResponse = array_merge($aResponse, $aResponse_link);

		echo json_encode($aResponse);
	}

	function saveMailerSettings() {
		$this->model_mailer->saveMailerSettings($_POST);
		$aResponse = array(
			"error" => FALSE,
			"description" => "Datele au fost salvate",
			"success" => TRUE
		);
		echo json_encode($aResponse);
	}

	/** ATASAMENTE**/
	function bringAttach() {

		$table = 'mailer_attach';
		$idMailer = $this->input->post("mailer_id");
		$sType = $this->input->post("type");
		$sort = "name";
		$dir = "asc";

		$s_limit = $this->input->post("start");
		$e_limit = $this->input->post("limit");
		echo json_encode($this->model_mailer->bringAttach($table, $idMailer, $sType, $s_limit, $e_limit, $sort, $dir));
	}

	/** LINKURI**/
	function bringLink() {

		$table = 'mailer_link';
		$idMailer = $this->input->post("mailer_id");
		$sort = $this->input->post("sort") ? $this->input->post("sort") : "link_nume";
		$dir = $this->input->post("dir") ? $this->input->post("dir") : "asc";

		$s_limit = $this->input->post("start");
		$e_limit = $this->input->post("limit");
		echo json_encode($this->model_mailer->bringLink($table, $idMailer, $s_limit, $e_limit, $sort, $dir));
	}

	function addAttach() {
		$mailer_id = $this->input->post("mailer_id");
		$type = $this->input->post("type");
		$this->load->library("attach_lib");

		if ($type == "image") {
			$aResult = $this->attach_lib->addImage($mailer_id);
		}
		if ($type == "attach") {
			$aResult = $this->attach_lib->addAttach($mailer_id);
		}

		echo json_encode($aResult);
	}

	function deleteAttach() {
		$this->model_mailer->deleteAttach($_POST);
		$aResponse = array(
			"error" => FALSE,
			"description" => "Datele au fost sterse",
			"success" => TRUE
		);
		echo json_encode($aResponse);
	}

	function sendMailer() {


		$aEmployees = $this->config->item("employeeContact");

		$idMailer = $this->input->post("idMailer");
		$path_full = $this->config->item('upload_path_full');

		$result = $this->model_mailer->getMailerSettings($idMailer);
		$resultLink = $this->model_mailer->bringLink("mailer_link", $idMailer, 0, 1000, "link_nume", "ASC");
		$resultLink = $resultLink["DS_LINK"];

		$this->load->plugin('phpmailer');
		$mail = new phpmailer(TRUE);

		$mail->IsHTML(TRUE);
		$mail->IsSMTP();
		$mail->SMTPAuth = TRUE;

		try {

			$mail->CharSet = "utf-8";
			
			$mail->Host = "mail.morethanpub.ro";
			$mail->Password = "officeoffice";
			$mail->Username = "office@morethanpub.ro";
			
			/*$mail->Host = "comunicatedirectmarketing.ro";
			$mail->Password = "marketing2006";
			$mail->Username = "office@comunicatedirectmarketing.ro";*/
			
			/*$mail->Password = "bookbook2013";
			$mail->Username = "bookland@comunicatedirectmarketing.ro";*/
			
			$mail->Port = 26;


			$mail->AddReplyTo($result->reply_email, $result->reply_name);
			$mail->SetFrom($result->from_email, $result->from_name);
			$mail->AddAddress($result->to_email);
			//You can add more emails

			$aAttachment = $this->model_mailer->bringAttach("mailer_attach", $idMailer, "attach", 0, 1000, "name", "asc");


			//print_r ($aAttachment);
			foreach ($aAttachment["DS_ATTACH"] as $attach) {

				if ($attach["name"] != '') {
					$filename = "././resources/uploads/attach/" . $attach["name"];
					if (file_exists($filename)) {
						$mail->AddAttachment($filename);
					} else {
						$aResponse = array(
							"error" => TRUE,
							"description" => "Un atasament nu exista",
							"type" => "Data"
						);
						echo json_encode($aResponse);
						return;
					}
				}

			}

			$body = $result->body;


			if ($result->test_sex == "2") {
				$header_lower = strtolower($result->header_m) . " " . $result->test_name;
				$header_title = ucfirst($result->header_m) . " " . $result->test_name;
				$header_ = $result->header_m . " " . $result->test_name;
			} elseif ($result->test_sex == "1") {
				$header_lower = strtolower($result->header_f) . " " . $result->test_name;
				$header_title = ucfirst($result->header_f) . " " . $result->test_name;
				$header_ = $result->header_f . " " . $result->test_name;
			} else {
				$header_lower = strtolower($result->header_n) . " " . $result->test_name;
				$header_title = ucfirst($result->header_n) . " " . $result->test_name;
				$header_ = $result->header_n . " " . $result->test_name;
			}

			$aName = explode(" ", $result->test_name);
			$sFirstName = $aName[0];
			$sLastName = $aName[1];

			$satelit = $this->config->item("mtp_satelit");
			$satelitDezabonare = $this->config->item("mtp_satelit_dezabonare");

			//creare link dezabonare
			$aLinkDezabonare = base64_encode("1" . "-**-" . md5("1" * 22));
			$aLinkDezabonare = str_replace("/", "_", $aLinkDezabonare);
			$aLinkDezabonare = $satelitDezabonare . $aLinkDezabonare;

			//replacing customizari nume
			$strReplace1 = array(
				"LOWER_HEADER",
				"TITLE_HEADER",
				"NAME",
				"_HEADER",
				"_DISCLAIMER",
				"_COMPANY",
				"_ADDRESS",
				"_PHONE",
				"_MOBIL",
				"_WEB",
				"_CUI",
				"_DOMAIN",
				"_SUBDOMAIN",
				"_EMAIL1",
				"_EMAIL2",
				"_POSITION",
				"_SUBPOSITION",
				"_EMPLOYEE",
				"_COUNTY",
				"_CITY",
				"PRENUME",
				"NUME",
				"_DEZABONAT"
			);
			$strReplace2 = array(
				$header_lower,
				$header_title,
				$result->test_name,
				$header_,
				$result->disclaimer,
				$result->test_company,
				$result->test_address,
				$result->test_phone,
				$result->test_mobil,
				$result->test_web,
				$result->test_cui,
				$result->test_domain_val,
				$result->test_subdomain_val,
				$result->test_email1,
				$result->test_email2,
				$result->test_position_val,
				$result->test_subposition_val,
				$aEmployees[$result->test_employee],
				$result->test_county_val,
				$result->test_city_val,
				$sFirstName,
				$sLastName,
				$aLinkDezabonare
			);



			foreach ($resultLink as $key => $aLink) {
				//pentru fiecare link se creaza un hash

				//client_person_id
				//link
				//link_nume - adr web

				//1 =  $aContact->client_persons_id
				/*echo     $aLink["link_nume"] . "**" . "1" . "**" . $aLink["link_cod"] . "**";
				 echo   $aLink["link_id"] + (1 * 22);
				 echo   md5($aLink["link_id"] + (1 * 22));
				 echo*/
				$aLinkEncoded = base64_encode($aLink["link_nume"] . "-**-" . 1 . "-**-" . $aLink["link_id"] . "-**-" . md5($aLink["link_id"] + (1 * 22)));
				$aLinkEncoded = str_replace("/", "_", $aLinkEncoded);
				$body = str_replace($aLink["link_cod"], $satelit . $aLinkEncoded, $body);
			}


			$body = str_replace($strReplace1, $strReplace2, $body);

			//imagini embedded
			$aAttachment = $this->model_mailer->bringAttach("mailer_attach", $idMailer, "image", 0, 1000, "name", "asc");
			foreach ($aAttachment["DS_IMAGE"] as $attach) {
				if ($attach["name"] != '') {
					$filename = "././resources/uploads/full/" . $attach["name"];
					if (file_exists($filename)) {
						$pattern = '/' . $attach["name"] . '/';
						preg_match_all($pattern, $body, $matches);

						if (count($matches[0]) > 0) {
							//scot calea relativa
							$body = str_replace($path_full, "", $body);
							//$sReplace="cid:".$attach["name"];
							$aReplace = explode(".", $attach["name"]);
							array_pop($aReplace);
							$base = implode(".", $aReplace);
							$sReplace2 = "cid:" . $base;

							$body = str_replace($attach["name"], $sReplace2, $body);
							$mail->AddEmbeddedImage($filename, $base, $attach["name"]);
						}

					} else {
						$aResponse = array(
							"error" => TRUE,
							"description" => "Un atasament nu exista",
							"type" => "Data"
						);
						echo json_encode($aResponse);
						return;
					}
				}

			}
			
			$mail->Subject = str_replace($strReplace1, $strReplace2, $result->subject);
			//creare culoare background
			$sBodyStyle = $result->body_style;

			$mail->Body = "<body {$sBodyStyle}>" . $body . "</body>";

			if (!$mail->Send()) {
				$aResponse = array(
					"error" => TRUE,
					"description" => "Emailul NU a fost trimis: " . $mail->ErrorInfo
				);
			} else {
				$aResponse = array(
					"error" => FALSE,
					"description" => "Emailul a fost trimis, pe bune!"
				);
			}
		} catch (phpmailerException $e) {
			$aResponse = array(
				"error" => TRUE,
				"description" => "Emailul NU a fost trimis: " . $e->errorMessage(),
				"type" => "email"
			);
		} catch (Exception $e) {
			$aResponse = array(
				"error" => TRUE,
				"description" => "Emailul NU a fost trimis: " . $e->getMessage(),
				"type" => "email"
			);
		}
		echo json_encode($aResponse);
	}

	/**  Inserare / editare linkuri
	 * @return void
	 */
	function operationLink() {
		$bResponse = $this->model_mailer->operationLink($_POST);
		if ($bResponse === TRUE) {
			$aResponse = array(
				"error" => false,
				"success" => true,
				"description" => "Datele au fost salvate"
			);
		} else {
			$aResponse = array(
				"error" => true,
				"description" => $bResponse,
				"type" => "Validare"
			);
		}
		echo json_encode($aResponse);
	}

	/**
	 * Functie care aduce datele despre unei inregistrari
	 * @return string json
	 */
	function getLink() {
		$aResult = $this->model_mailer->getLink($this->aPost);
		echo json_encode(array(
			"error" => false,
			"data" => $aResult
		));
	}

	function deleteLink() {
		$this->model_mailer->deleteLink($_POST);
		$aResponse = array(
			"error" => FALSE,
			"description" => "Datele au fost sterse",
			"success" => TRUE
		);
		echo json_encode($aResponse);
	}

}

/* End of file Mailer.php */
/* Location: ./system/application/controllers/admin/Mailer.php */
